const cloud = require('wx-server-sdk')

cloud.init()

const WEEK_OFFSET = 7 * 24 * 60 * 60 * 1000;

/// (skip: TimestampMillis = Date.now(), duration: TimestamMillis = WEEK_OFFSET, limit: int = 20) -> (result: DbQueryResult<Delivery>)
exports.main = async (event) => {
  const skip = event.skip || Date.now();
  const duration = event.duration || WEEK_OFFSET;
  const limit = event.limit || 20;

  const db = cloud.database();

  const borrowingResults = await db.collection('deliveries').aggregate().match({
    time: db.command.gt(skip - duration).lt(skip),
    _type: db.command.eq('borrow')
  }).limit(limit).lookup({
    from: 'pool',
    localField: 'id',
    foreignField: '_id',
    as: 'record'
  }).end();
  const returningResults = await db.collection('deliveries').aggregate().match({
    time: db.command.gt(skip - duration).lt(skip),
    _type: db.command.eq('return')
  }).limit(limit).lookup({
    from: 'pool',
    localField: 'id',
    foreignField: '_id',
    as: 'record'
  }).end();

  return {
    result: {
      data: borrowingResults.list.concat(returningResults.list)
    }
  };
}
